#include "advancesettingpage.h"
#include "ui_advancesettingpage.h"
#include "smallblock.h"
#include "../model/osdutilsmodel.h"
#include "../model/osdremoteservicemodel.h"
#include "../sys/sysconfighandler.h"
#include "advancesetworker.h"
#include "../osdglobal.h"
#include "../control/msgpagecontroller.h"
#include <QKeyEvent>
#include <QDebug>
#include "../control/mainwindowcontroller.h"
#include "../control/keyboardcontroller.h"
#include "viewglobal.h"
#include <QMargins>
#include <QGraphicsDropShadowEffect>
#include "voluecontrol.h"
#include <QTimer>
#include <QTime>

#define NET_SETTING_DHCP        ("block_net_dhcp")
#define NET_SETTING_IP          ("block_net_ip")
#define NET_SETTING_MUSK        ("block_net_musk")
#define NET_SETTING_GATEWAY     ("block_net_gateway")
#define NET_SETTING_DNS         ("block_net_dns")
#define CALL_RATE               ("block_call_rate")
#define AUTO_RELAY              ("block_auto_relay")
#define AUTO_NO_VOICE           ("block_auto_voice")
#define AUTO_BLACK              ("block_auto_black")
#define MEET_TIP                ("block_meet_tip")
#define HASH                    ("block_hash")

AdvanceSettingPage::AdvanceSettingPage(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::AdvanceSettingPage),
    m_inUpdate(0)
{
    ui->setupUi(this);
    m_currentRate = "";

    m_upprocess = new VolueControl(this);
    ui->upprocess_layout->addWidget(m_upprocess);
    m_upprocess->setMaximumWidth(500);
    m_upprocess->setMinimumWidth(500);
    m_upprocess->setMaximumHeight(20);
    m_upprocess->setMinimumHeight(20);
    m_upprocess->hide();
    ui->uptip_label->hide();

    initNetSettingWidget();
    initCallSettingWidget();
    initFocusOrder();


    connect(&OSDRemoteServiceModel::instance(),
            SIGNAL(notifyConfigInfo(ConfigInfo)),
            this, SLOT(configSlot(ConfigInfo)));

    connect(&OSDRemoteServiceModel::instance(),
            SIGNAL(notifyVersion(NewVersionInfo)),
            this, SLOT(newVersionSlot(NewVersionInfo)));

    connect(&OSDRemoteServiceModel::instance(),
            SIGNAL(notifyNetworkStatus(NetworkInfo)),
            this, SLOT(networkStatusSlot(NetworkInfo)));

    connect(&OSDRemoteServiceModel::instance(),
            SIGNAL(notifySystemStatus(SystemStatusInfo)),
            this, SLOT(sysStatusSlot(SystemStatusInfo)));

    connect(&OSDRemoteServiceModel::instance(),
            SIGNAL(notifyModifyNetwork(BaseResp)),
            this, SLOT(modifyNetworkResponseSlot(BaseResp)));

    connect(&OSDRemoteServiceModel::instance(),
            SIGNAL(notifyUpgrade(BaseResp)),
            this, SLOT(updateResponseSlot(BaseResp)));

    connect(&OSDRemoteServiceModel::instance(),
            SIGNAL(notifyModifyConfig(BaseResp)),
            this, SLOT(modifyConfigResponseSlot(BaseResp)));

    worker = new AdvanceSetWorker;
    connect(this, SIGNAL(updateStatus(int)), worker, SLOT(work(int)));

    timer = new QTimer(this);
    connect(timer, SIGNAL(timeout()),this,SLOT(refreshSysStatus()));


    timerquit = new QTimer(this);
    connect(timerquit, SIGNAL(timeout()),this,SLOT(reboot()));

    ui->pbNetSet->setChecked(true);
    ui->stackedWidget->setCurrentWidget(ui->netsetting);
    ui->pbNetSet->installEventFilter(this);
    ui->pbCallSet->installEventFilter(this);
    ui->pbDeviceSet->installEventFilter(this);
    ui->pbUpdateSet->installEventFilter(this);
    ui->pushButton->installEventFilter(this);
    ui->pbUpdate->installEventFilter(this);
}

AdvanceSettingPage::~AdvanceSettingPage()
{
    workThread.quit();
    workThread.wait();
    delete worker;
    delete ui;
}

void AdvanceSettingPage::configSlot(ConfigInfo rv)
{
    QString key = rv.getKey();
    QString value = rv.getValue();
    if (rv.getKey() == "call_rate")
    {
        value = rv.getValue()+"|"+rv.getRange();
    }
    updateConfig(key,value);
}

void AdvanceSettingPage::newVersionSlot(NewVersionInfo rv)
{
    updateConfig("version",rv.getVersion());
}

void AdvanceSettingPage::refreshSysStatus()
{
    OSDRemoteServiceModel::instance().systemStatus();
}

void AdvanceSettingPage::sysStatusSlot(SystemStatusInfo rv)
{
    double total = rv.getDiskTotal().toDouble()/(1024*1024*1024);

    double used = 0.0;
    if (rv.getDiskTotal().toDouble() > 0.0)
    {
        used = rv.getDiskUsed().toDouble()/rv.getDiskTotal().toDouble();
    }
    QString str = "";
    if (total == 0)
    {
        str = QString("总容量%1T").arg(0)
                +" "+QString("已使用%1%").arg(0);
    }
    else
    {
        str = QString("总容量%1T").arg(QString::number(total,'f',1))
                +" "+QString("已使用%1%").arg(QString::number(used*100,'f',2));
    }

    qlonglong duration = rv.getRuntime().toLongLong();
    int day = duration/(60*60*24);
    QString runtime = "";
    qlonglong rest = duration;
    if (day > 0)
    {
        runtime += QString("%1天").arg(day) + QString(" ");
        rest = rest % (60*60*24);
    }
    qlonglong hour = rest / (60*60);
    if (hour > 0)
    {
        runtime += QString("%1时").arg(hour) + QString(" ");
        rest = rest % (60*60);
    }

    qlonglong min = rest / 60;
    if (min > 0)
    {
        runtime += QString("%1分").arg(min) + QString(" ");
        rest = rest % (60);
    }

    runtime += QString("%1秒").arg(rest);

    if(rv.getIsSuccess())
    {
        updateSysInfo(QString("正常"),
                     runtime,
                     rv.getResource()+"%",
                     str);
    }
    else
    {
        updateSysInfo(QString("异常"),
                     "",
                     "",
                     "");
    }
}

void AdvanceSettingPage::networkStatusSlot(NetworkInfo rv)
{
    updateNetInfo(rv.getIp(),rv.getMask(),rv.getGateway(),rv.getDns());
}

void AdvanceSettingPage::setItemIndex(QString name, int index)
{
    SmallBlock* block = this->findChild<SmallBlock*>(name);
    if (block)
    {
        block->setOption(index);
    }
}

void AdvanceSettingPage::updateNetInfo(QString ip,
                                       QString mask,
                                       QString gateway,
                                       QString dns)
{
    SmallBlock* block = this->findChild<SmallBlock*>(NET_SETTING_IP);
    if (block)
    {
        block->setText(ip);
        SysConfigHandler::instance().setIP(ip);
    }

    block = this->findChild<SmallBlock*>(NET_SETTING_MUSK);
    if (block)
    {
        block->setText(mask);
        SysConfigHandler::instance().setMask(mask);
    }

    block = this->findChild<SmallBlock*>(NET_SETTING_GATEWAY);
    if (block)
    {
        block->setText(gateway);
        SysConfigHandler::instance().setGateway(gateway);
    }

    block = this->findChild<SmallBlock*>(NET_SETTING_DNS);
    if (block)
    {
        block->setText(dns);
        SysConfigHandler::instance().setDns(dns);
    }
}

void AdvanceSettingPage::updateConfig(QString key, QString value)
{
    if (key == QString("version"))
    {
        if(value.isEmpty())
        {
            ui->label_6->setText("当前已是最新版本");
            ui->pbUpdate->hide();
        }
        else
        {
            ui->label_6->setText(QString("最新版本：")+value+"，请升级");
            ui->pbUpdate->show();
            ui->uptip_label->setText("");
            ui->uptip_label->hide();
        }
        return;
    }

    int index = m_strIndex.value(value,0);
    QString keyStr = "";
    if (key == QString("enable_dhcp"))
    {
        keyStr = NET_SETTING_DHCP;
    }
    else if (key == QString("call_rate"))
    {
        m_indexStr.clear();
        keyStr = CALL_RATE;

        QStringList list = value.split("|");
        if (list.count() < 1)
        {
            return;
        }
        QString vi = list[0];
        list.removeAt(0);

        QHash<QString, int> hashMap;
        hashMap.clear();
        int i = 0;
        QStringList ratestr;
        foreach(QString item, list)
        {
            QStringList vs = item.split("@");
            if (vs.count() < 2)
            {
                continue;
            }
            m_indexStr.insert(i,vs[1]);
            hashMap.insert(vs[1],i);
            i += 1;
            ratestr << vs[0];
        }
        index = hashMap.value(vi,0);
        SmallBlock* block = this->findChild<SmallBlock*>(CALL_RATE);
        if (block)
        {
            block->setSelectionList(ratestr,value);
        }

        SysConfigHandler::instance().setCallRate(vi);
    } else if (key == QString("auto_answer"))
    {
        keyStr = AUTO_RELAY;
    } else if (key == QString("auto_mute_audio"))
    {
        keyStr = AUTO_NO_VOICE;
    }else if (key == QString("auto_suspend_video"))
    {
        keyStr = AUTO_BLACK;
    }else if (key == QString("conference_tips"))
    {
        keyStr = MEET_TIP;
    }

    setItemIndex(keyStr, index);
}

void AdvanceSettingPage::updateSysInfo(QString status, QString time,
                   QString resource, QString disk)
{
    ui->status_label->setText(status);
    ui->runtime_label->setText(time);
    ui->cpu_label->setText(resource);
    ui->disk_label->setText(disk);
}

bool AdvanceSettingPage::eventFilter(QObject *o, QEvent *e)
{
    if (ui->pbNetSet == o && e->type() == QEvent::FocusIn)
    {
        timer->stop();
        ui->pbNetSet->setChecked(true);
        ui->stackedWidget->setCurrentWidget(ui->netsetting);
        emit updateStatus(0);
        return true;
    } else if (ui->pbCallSet == o && e->type() == QEvent::FocusIn)
    {
        timer->stop();
        ui->pbCallSet->setChecked(true);
        ui->stackedWidget->setCurrentWidget(ui->callsetting);
        emit updateStatus(1);
        return true;
    } else if (ui->pbUpdateSet == o && e->type() == QEvent::FocusIn)
    {
        timer->stop();
        ui->pbUpdateSet->setChecked(true);
        ui->stackedWidget->setCurrentWidget(ui->updatesetting);
        emit updateStatus(2);
        return true;
    } else if (ui->pbDeviceSet == o && e->type() == QEvent::FocusIn)
    {
        timer->start(1000);
        ui->pbDeviceSet->setChecked(true);
        ui->stackedWidget->setCurrentWidget(ui->devicesetting);
        emit updateStatus(3);
        return true;
    }
    else if (e->type() == QEvent::KeyPress)
    {
        if (QString(o->metaObject()->className()) == QString("SmallBlock"))
        {
            return false;
        }
        return true;
    }
    else if (e->type() == QEvent::KeyRelease)
    {
        QKeyEvent *ke = dynamic_cast<QKeyEvent*>(e);
        if (ke && (ke->key() == Qt::Key_Right
                   || ke->key() == Qt::Key_Down
                   || ke->key() == Qt::Key_Left
                   || ke->key() == Qt::Key_Up))
        {
            if (!m_ctrlOrder.contains(o))
            {
                return false;
            }

            if ((ke->key() == Qt::Key_Right || ke->key() == Qt::Key_Left)
             && (o == this->findChild<SmallBlock*>(NET_SETTING_IP)
                || o == this->findChild<SmallBlock*>(NET_SETTING_MUSK)
                || o == this->findChild<SmallBlock*>(NET_SETTING_GATEWAY)
                || o == this->findChild<SmallBlock*>(NET_SETTING_DNS) ))
            {

                SmallBlock* s = dynamic_cast<SmallBlock*>(o);
                if (s->lineEdit()->hasFocus())
                {
                    int pos = s->getCursorPos();
                    if (pos >= 0 && pos <= (s->getText().length()))
                        return false;
                }
            }

            QObject *target = m_ctrlOrder.value(o).at(OSDUtilsModel::instance().keyIndex(ke->key()));
            if (target)
            {
                QWidget* w = dynamic_cast<QWidget*>(target);
                if (w) w->setFocus();
            }
            return true;
        }else if (ke && ke->key() == Qt::Key_Escape)
        {
            MainWindowController::instance().changeSubPage(OSD::ViewGlobal::SUB_PAGE_INDEX);
            return true;
        }
    }

    if (ui->pushButton == o)
    {
        if (e->type() == QEvent::FocusIn)
        {
            QGraphicsDropShadowEffect *pEffect = new QGraphicsDropShadowEffect(ui->pushButton);
            pEffect->setOffset(0, 0);
            pEffect->setColor(QColor(41, 163, 255, 255));
            pEffect->setBlurRadius(30);
            ui->pushButton->setGraphicsEffect(pEffect);
            return true;
        }
        else if (e->type() == QEvent::FocusOut)
        {
            ui->pushButton->setGraphicsEffect(NULL);
            return true;
        }else if (e->type() == QEvent::MouseButtonRelease)
        {
            on_pushButton_clicked();
        }
    }

    if (ui->pbUpdate == o)
    {
        if (e->type() == QEvent::FocusIn)
        {
            QGraphicsDropShadowEffect *pEffect = new QGraphicsDropShadowEffect(ui->pushButton);
            pEffect->setOffset(0, 0);
            pEffect->setColor(QColor(41, 163, 255, 255));
            pEffect->setBlurRadius(30);
            ui->pbUpdate->setGraphicsEffect(pEffect);
            return true;
        }
        else if (e->type() == QEvent::FocusOut)
        {
            ui->pbUpdate->setGraphicsEffect(NULL);
            return true;
        }else if (e->type() == QEvent::MouseButtonRelease)
        {
            on_pbUpdate_clicked();
        }
    }

    return false;
}

void AdvanceSettingPage::modifyConfigResponseSlot(BaseResp rv)
{
    if (rv.getIsSuccess())
    {
        SmallBlock *block = NULL;
        if (rv.baseName() == QString("enable_dhcp"))
        {
            OSDRemoteServiceModel::instance().config("enable_dhcp");
            QTime n=QTime::currentTime();
            QTime now;
            do{
                now=QTime::currentTime();
            }   while(n.msecsTo(now)<=5000);
            OSDRemoteServiceModel::instance().networkStatus();
            return;
        }
        else if (rv.baseName() == QString("auto_answer"))
        {
            block = this->findChild<SmallBlock*>(AUTO_RELAY);
        }
        else if (rv.baseName() == QString("auto_mute_audio"))
        {
            block = this->findChild<SmallBlock*>(AUTO_NO_VOICE);
        }
        else if (rv.baseName() == QString("auto_suspend_video"))
        {
            block = this->findChild<SmallBlock*>(AUTO_BLACK);
        }
        else if (rv.baseName() == QString("conference_tips"))
        {
            block = this->findChild<SmallBlock*>(MEET_TIP);
        }
        else if (rv.baseName() == QString("call_rate"))
        {
            block = this->findChild<SmallBlock*>(CALL_RATE);
        }

        if (!block) return;

        block->changeOption();
        if (rv.baseName() == QString("call_rate"))
        {
            SysConfigHandler::instance().setCallRate(m_currentRate);
        }
    }
}

void AdvanceSettingPage::yesnoChanged(int next)
{
    SmallBlock *block = dynamic_cast<SmallBlock *>(sender());

    if (!block)
        return;

    QString key = "";
    if (QString(block->objectName()) == QString(NET_SETTING_DHCP))
    {
        key = "enable_dhcp";
    }
    else if (QString(block->objectName()) == QString(AUTO_RELAY))
    {
        key = "auto_answer";
    }
    else if (QString(block->objectName()) == QString(AUTO_NO_VOICE))
    {
        key = "auto_mute_audio";
    }
    else if (QString(block->objectName()) == QString(AUTO_BLACK))
    {
        key = "auto_suspend_video";
    }
    else if (QString(block->objectName()) == QString(MEET_TIP))
    {
        key = "conference_tips";
    }else if (QString(block->objectName()) == QString(HASH))
    {
        key = "encryption_mode";
    }

    if (key.isEmpty()) return;

    OSDRemoteServiceModel::instance().modifyConfig(key,
                         next == 0 ? "true":"false");
}

void AdvanceSettingPage::callrateChanged(int next)
{
    SmallBlock *block = dynamic_cast<SmallBlock *>(sender());

    if (!block)
        return;
    QString key = "call_rate";

    m_currentRate = m_indexStr.value(next);
    OSDRemoteServiceModel::instance().modifyConfig(key,
                         m_indexStr.value(next));
}

void AdvanceSettingPage::initFocusOrder()
{
    QList<QObject *> orderlist;
    orderlist.clear();
    orderlist<< ui->pbCallSet << ui->pbDeviceSet << NULL << ui->pbUpdate;
    m_ctrlOrder.insert(ui->pbUpdateSet, orderlist);

    orderlist.clear();
    orderlist<< NULL << NULL << ui->pbUpdateSet << NULL;
    m_ctrlOrder.insert(ui->pbUpdate, orderlist);

    orderlist.clear();
    orderlist<< ui->pbUpdateSet << NULL << NULL << NULL;
    m_ctrlOrder.insert(ui->pbDeviceSet, orderlist);
}

void AdvanceSettingPage::initNetSettingWidget()
{
    SmallBlock *dhcp_block = new SmallBlock;
    dhcp_block->setMaximumSize(500,120);
    dhcp_block->setMinimumSize(500,120);
    dhcp_block->setObjectName(NET_SETTING_DHCP);
    dhcp_block->setTitleLabel("打开DHCP");
    dhcp_block->setParent(this);
    QStringList list;
    list << "是" << "否";
    dhcp_block->setSelectionList(list,"是");
    ui->dhcp_layout->addWidget(dhcp_block);
    dhcp_block->installEventFilter(this);
    connect(dhcp_block, SIGNAL(optionChangeSig(int)), this, SLOT(yesnoChanged(int)));
    connect(dhcp_block, SIGNAL(selctionChanged(QString)), this, SLOT(dealDHCP(QString)));

    m_strIndex.insert("true",0);
    m_strIndex.insert("false",1);

    SmallBlock *ip_block = new SmallBlock(0);
    ip_block->setObjectName(NET_SETTING_IP);
    ip_block->setMaximumSize(500,120);
    ip_block->setMinimumSize(500,120);
    ip_block->setTitleLabel("IP");
    ip_block->setText("");
    ip_block->setLineEditValidator(STR_IP_REGEXP);
    ip_block->setParent(this);
    ip_block->setLineEditPlaceHolder("请输入IP地址");
    ui->ip_layout->addWidget(ip_block);
    ip_block->installEventFilter(this);
//    connect(ip_block, SIGNAL(textStartSig()), this, SLOT(showKeyBoard()));
//    connect(ip_block, SIGNAL(receiveEnter()), this, SLOT(receiveInput()));

    SmallBlock *musk_block = new SmallBlock(0);
    musk_block->setObjectName(NET_SETTING_MUSK);
    musk_block->setMaximumSize(500,120);
    musk_block->setMinimumSize(500,120);
    musk_block->setTitleLabel("子网掩码");
    musk_block->setText("");
    musk_block->setLineEditValidator(STR_IP_REGEXP);
    musk_block->setParent(this);
    musk_block->setLineEditPlaceHolder("请输入子网掩码");
    ui->musk_layout->addWidget(musk_block);
    musk_block->installEventFilter(this);
//    connect(musk_block, SIGNAL(textStartSig()), this, SLOT(showKeyBoard()));
//    connect(musk_block, SIGNAL(receiveEnter()), this, SLOT(receiveInput()));

    SmallBlock *gateway_block = new SmallBlock(0);
    gateway_block->setObjectName(NET_SETTING_GATEWAY);
    gateway_block->setMaximumSize(500,120);
    gateway_block->setMinimumSize(500,120);
    gateway_block->setTitleLabel("网关");
    gateway_block->setText("");
    gateway_block->setLineEditValidator(STR_IP_REGEXP);
    gateway_block->setParent(this);
    gateway_block->setLineEditPlaceHolder("请输入网关地址");
    ui->gateway_layout->addWidget(gateway_block);
    gateway_block->installEventFilter(this);
//    connect(gateway_block, SIGNAL(textStartSig()), this, SLOT(showKeyBoard()));
//    connect(gateway_block, SIGNAL(receiveEnter()), this, SLOT(receiveInput()));

    SmallBlock *dns_block = new SmallBlock(0);
    dns_block->setObjectName(NET_SETTING_DNS);
    dns_block->setMaximumSize(500,120);
    dns_block->setMinimumSize(500,120);
    dns_block->setTitleLabel("DNS");
    dns_block->setText("");
    dns_block->setLineEditValidator(STR_IP_REGEXP);
    dns_block->setParent(this);
    dns_block->setLineEditPlaceHolder("请输入DNS");
    ui->dnsLayout->addWidget(dns_block);
    dns_block->installEventFilter(this);

    QList<QObject *> orderlist;
    orderlist.clear();
    orderlist<< NULL << ui->pbCallSet << NULL << dhcp_block;
    m_ctrlOrder.insert(ui->pbNetSet, orderlist);

    orderlist.clear();
    orderlist<< NULL << musk_block << ui->pbNetSet << ip_block;
    m_ctrlOrder.insert(dhcp_block, orderlist);

    orderlist.clear();
    orderlist<< NULL << gateway_block << dhcp_block << NULL;
    m_ctrlOrder.insert(ip_block, orderlist);

    orderlist.clear();
    orderlist<< dhcp_block << dns_block << ui->pbNetSet << gateway_block;
    m_ctrlOrder.insert(musk_block, orderlist);

    orderlist.clear();
    orderlist<< ip_block << dns_block << musk_block << NULL;
    m_ctrlOrder.insert(gateway_block, orderlist);

    orderlist.clear();
    orderlist<< musk_block << ui->pushButton << ui->pbNetSet << NULL;
    m_ctrlOrder.insert(dns_block, orderlist);

    orderlist.clear();
    orderlist<< dns_block << NULL << ui->pbNetSet << NULL;
    m_ctrlOrder.insert(ui->pushButton, orderlist);
}

void AdvanceSettingPage::initCallSettingWidget()
{
    SmallBlock *rate_block = new SmallBlock;
    rate_block->setObjectName(CALL_RATE);
    rate_block->setMaximumSize(500,120);
    rate_block->setMinimumSize(500,120);
    rate_block->setTitleLabel("呼叫速率");
    rate_block->setParent(this);
    QStringList list;
    ui->rate_layout->addWidget(rate_block);
    rate_block->installEventFilter(this);
    connect(rate_block, SIGNAL(optionChangeSig(int)), this, SLOT(callrateChanged(int)));

    SmallBlock *autorelay_block = new SmallBlock;
    autorelay_block->setObjectName(AUTO_RELAY);
    autorelay_block->setMaximumSize(500,120);
    autorelay_block->setMinimumSize(500,120);
    autorelay_block->setTitleLabel("自动应答");
    autorelay_block->setParent(this);
    list.clear();
    list << "启用" << "取消";
    autorelay_block->setSelectionList(list,"启用");
    ui->autorelay_layout->addWidget(autorelay_block);
    autorelay_block->installEventFilter(this);
    connect(autorelay_block, SIGNAL(optionChangeSig(int)), this, SLOT(yesnoChanged(int)));

    SmallBlock *autonov_block = new SmallBlock;
    autonov_block->setObjectName(AUTO_NO_VOICE);
    autonov_block->setMaximumSize(500,120);
    autonov_block->setMinimumSize(500,120);
    autonov_block->setTitleLabel("自动静音");
    autonov_block->setParent(this);
    autonov_block->setSelectionList(list,"取消");
    ui->autonov_layout->addWidget(autonov_block);
    autonov_block->installEventFilter(this);
    connect(autonov_block, SIGNAL(optionChangeSig(int)), this, SLOT(yesnoChanged(int)));

    SmallBlock *autoblack_block = new SmallBlock;
    autoblack_block->setObjectName(AUTO_BLACK);
    autoblack_block->setMaximumSize(500,120);
    autoblack_block->setMinimumSize(500,120);
    autoblack_block->setTitleLabel("自动屏蔽视频");
    autoblack_block->setParent(this);
    autoblack_block->setSelectionList(list,"取消");
    ui->autoblack_layout->addWidget(autoblack_block);
    autoblack_block->installEventFilter(this);
    connect(autoblack_block, SIGNAL(optionChangeSig(int)), this, SLOT(yesnoChanged(int)));

    SmallBlock *meettip_block = new SmallBlock;
    meettip_block->setObjectName(MEET_TIP);
    meettip_block->setMaximumSize(500,120);
    meettip_block->setMinimumSize(500,120);
    meettip_block->setTitleLabel("会议提示");
    meettip_block->setParent(this);
    meettip_block->setSelectionList(list,"启用");
    ui->meettip_layout->addWidget(meettip_block);
    meettip_block->installEventFilter(this);
    connect(meettip_block, SIGNAL(optionChangeSig(int)), this, SLOT(yesnoChanged(int)));

//    SmallBlock *hash_block = new SmallBlock;
//    hash_block->setObjectName(HASH);
//    hash_block->setMaximumSize(500,120);
//    hash_block->setMinimumSize(500,120);
//    hash_block->setTitleLabel("加密");
//    hash_block->setParent(this);
//    hash_block->setSelectionList(list,"加密");
//    ui->hash_layout->addWidget(hash_block);
//    hash_block->installEventFilter(this);
//    connect(hash_block, SIGNAL(optionChangeSig(int)), this, SLOT(yesnoChanged(int)));

    QList<QObject *> orderlist;
    orderlist.clear();
    orderlist<< ui->pbNetSet << ui->pbUpdateSet << NULL << rate_block;
    m_ctrlOrder.insert(ui->pbCallSet, orderlist);

    orderlist.clear();
    orderlist<< NULL << autonov_block << ui->pbCallSet << autorelay_block;
    m_ctrlOrder.insert(rate_block, orderlist);

    orderlist.clear();
    orderlist<< NULL << autoblack_block << rate_block << NULL;
    m_ctrlOrder.insert(autorelay_block, orderlist);

    orderlist.clear();
    orderlist<< rate_block << meettip_block << ui->pbCallSet << autoblack_block;
    m_ctrlOrder.insert(autonov_block, orderlist);

    orderlist.clear();
    orderlist<< autorelay_block << meettip_block << autonov_block << NULL;
    m_ctrlOrder.insert(autoblack_block, orderlist);

    orderlist.clear();
    orderlist<< autonov_block << NULL << ui->pbCallSet << NULL;
    m_ctrlOrder.insert(meettip_block, orderlist);

//    orderlist.clear();
//    orderlist<< autoblack_block << NULL << meettip_block << NULL;
//    m_ctrlOrder.insert(hash_block, orderlist);
}

void AdvanceSettingPage::showKeyBoard()
{
    QObject *o = sender();
    QLineEdit *lineedit = dynamic_cast<SmallBlock *>(o)->lineEdit();
    KeyBoardController::instance().show(lineedit,0);
    if (o == this->findChild<SmallBlock*>(NET_SETTING_MUSK)
       || o == this->findChild<SmallBlock*>(NET_SETTING_GATEWAY))
    {
        QMargins margins = ui->verticalLayout_5->contentsMargins();
        margins.setTop(0);
        ui->verticalLayout_5->setContentsMargins(margins);
    }
}

void AdvanceSettingPage::receiveInput()
{
    QMargins margins = ui->verticalLayout_5->contentsMargins();
    if (margins.top() == 0)
    {
        margins.setTop(97);
        ui->verticalLayout_5->setContentsMargins(margins);
    }
}

void AdvanceSettingPage::lineEditFinish(QString txt)
{
    Q_UNUSED(txt);

    QMargins margins = ui->verticalLayout_5->contentsMargins();
    if (margins.top() == 0)
    {
        margins.setTop(97);
        ui->verticalLayout_5->setContentsMargins(margins);
    }
}

void AdvanceSettingPage::dealDHCP(QString value)
{
    if (value == "是")
    {
        if (this->findChild<SmallBlock*>(NET_SETTING_IP))
        {
            this->findChild<SmallBlock*>(NET_SETTING_IP)->setBlockEnable(false);
        }
        if (this->findChild<SmallBlock*>(NET_SETTING_MUSK))
        {
            this->findChild<SmallBlock*>(NET_SETTING_MUSK)->setBlockEnable(false);
        }
        if (this->findChild<SmallBlock*>(NET_SETTING_GATEWAY))
        {
            this->findChild<SmallBlock*>(NET_SETTING_GATEWAY)->setBlockEnable(false);
        }
        if (this->findChild<SmallBlock*>(NET_SETTING_DNS))
        {
            this->findChild<SmallBlock*>(NET_SETTING_DNS)->setBlockEnable(false);
        }
        ui->pushButton->hide();
    }
    else
    {
        if (this->findChild<SmallBlock*>(NET_SETTING_IP))
        {
            this->findChild<SmallBlock*>(NET_SETTING_IP)->setBlockEnable(true);
        }
        if (this->findChild<SmallBlock*>(NET_SETTING_MUSK))
        {
            this->findChild<SmallBlock*>(NET_SETTING_MUSK)->setBlockEnable(true);
        }
        if (this->findChild<SmallBlock*>(NET_SETTING_GATEWAY))
        {
            this->findChild<SmallBlock*>(NET_SETTING_GATEWAY)->setBlockEnable(true);
        }
        if (this->findChild<SmallBlock*>(NET_SETTING_DNS))
        {
            this->findChild<SmallBlock*>(NET_SETTING_DNS)->setBlockEnable(true);
        }
        ui->pushButton->show();
    }
}

void AdvanceSettingPage::modifyNetworkResponseSlot(BaseResp rv)
{
    QString ip = "";
    QString mask = "";
    QString gateway = "";
    QString dns = "";
    if (this->findChild<SmallBlock*>(NET_SETTING_IP))
    {
        ip = this->findChild<SmallBlock*>(NET_SETTING_IP)->getText();
    }
    if (this->findChild<SmallBlock*>(NET_SETTING_MUSK))
    {
        mask = this->findChild<SmallBlock*>(NET_SETTING_MUSK)->getText();
    }
    if (this->findChild<SmallBlock*>(NET_SETTING_GATEWAY))
    {
        gateway = this->findChild<SmallBlock*>(NET_SETTING_GATEWAY)->getText();
    }
    if (this->findChild<SmallBlock*>(NET_SETTING_DNS))
    {
        dns = this->findChild<SmallBlock*>(NET_SETTING_DNS)->getText();
    }

    if (rv.getIsSuccess())
    {
        SysConfigHandler::instance().setIP(ip);
        SysConfigHandler::instance().setMask(mask);
        SysConfigHandler::instance().setGateway(gateway);
        SysConfigHandler::instance().setDns(dns);
        //立即通知mainwindow刷新界面
        MainWindowController::instance().updateIP(ip);
    }
    else
    {
        //提示错误信息
        MsgPageController::instance().showMsg(rv.getCodeString());
    }
}

void AdvanceSettingPage::on_pushButton_clicked()
{
    //修改网络
    QString ip = "";
    QString mask = "";
    QString gateway = "";
    QString dns = "";
    if (this->findChild<SmallBlock*>(NET_SETTING_IP))
    {
        ip = this->findChild<SmallBlock*>(NET_SETTING_IP)->getText();
    }
    if (this->findChild<SmallBlock*>(NET_SETTING_MUSK))
    {
        mask = this->findChild<SmallBlock*>(NET_SETTING_MUSK)->getText();
    }
    if (this->findChild<SmallBlock*>(NET_SETTING_GATEWAY))
    {
        gateway = this->findChild<SmallBlock*>(NET_SETTING_GATEWAY)->getText();
    }
    if (this->findChild<SmallBlock*>(NET_SETTING_DNS))
    {
        dns = this->findChild<SmallBlock*>(NET_SETTING_DNS)->getText();
    }

    //检查
    QString errstr = "";
    if (ip.isEmpty())
    {
        errstr = "ip地址不能为空";
    }
    if (mask.isEmpty())
    {
        errstr = "子网掩码不能为空";
    }
    if (gateway.isEmpty())
    {
        errstr = "网关不能为空";
    }
    if (dns.isEmpty())
    {
        errstr = "DNS不能为空";
    }

    if (!errstr.isEmpty())
    {
        MsgPageController::instance().showMsg(errstr);
        return;
    }

    //修改网络
    OSDRemoteServiceModel::instance().modifyNetwork(ip,mask,gateway,dns);
}

void AdvanceSettingPage::showEvent(QShowEvent *e)
{
    ui->version_label->setText(SysConfigHandler::instance().version());
    QWidget::showEvent(e);
    ui->pbNetSet->setFocus();
    if (m_inUpdate)
    {
        ui->uptip_label->show();
        ui->uptip_label->setText("正在升级");
    }
    else
    {
        ui->uptip_label->hide();
        ui->uptip_label->setText("");
    }
}

void AdvanceSettingPage::hideEvent(QHideEvent *e)
{
    timer->stop();
    QWidget::hideEvent(e);
}

void AdvanceSettingPage::reboot()
{
    static int n = 5;
    QString tip = QString("升级成功，即将重启 %1s");
    ui->uptip_label->setText(tip.arg(n));
    n -= 1;
    if (n == 0)
    {
        timerquit->stop();
        OSDRemoteServiceModel::instance().reboot();
    }
}

void AdvanceSettingPage::updateResponseSlot(BaseResp rv)
{
    m_inUpdate = 0;
    if (rv.getIsSuccess())
    {
        ui->uptip_label->show();
        reboot();
        timerquit->start(1000);
    }
    else
    {
        ui->uptip_label->setText(rv.getCodeString());
    }
}

void AdvanceSettingPage::on_pbUpdate_clicked()
{
    ui->pbUpdate->hide();
    ui->uptip_label->show();
    ui->uptip_label->setText("正在升级");
    m_inUpdate = 1;
    OSDRemoteServiceModel::instance().upgrade();
}
